package com.zhsource.auth;

import cn.hutool.core.util.ObjUtil;

import com.zhsource.exception.GlobalException;
import com.zhsource.system.domain.Logininfo;
import com.zhsource.system.mapper.LogininfoMapper;
import com.zhsource.system.mapper.PermissionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    /**
     * 在登录的业务层中的authenticationManager.authenticate中会自动来调用这个方法
     * @param username 会把用户的账号给你
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1.获取用户信息
        String[] userNameAndTypeArr = username.split("-");
        String userName = userNameAndTypeArr[0];
        String type = userNameAndTypeArr[1];
        Logininfo logininfo = logininfoMapper.loadUserByUsername(userName, type);

        // 2.判断用户信息是否存在
        if (ObjUtil.isEmpty(logininfo)){
            throw new GlobalException("账号或密码错误！");
        }

        // 3.判断用户是否是后台用户，如果是后台用户需要去查询用户的权限
        List<String> permissionSns = null;
        if ("0".equals(type)){
            permissionSns = permissionMapper.selectPermissionSnByLogininfoId(logininfo.getId());
        }

        // 4.响应security所需要的接口的儿子
        return new SecurityUserDetails(logininfo, permissionSns);
    }
}
